#include <iostream>
#include <memory>
using std::cout;
using std::endl;
using std::unique_ptr;
using std::shared_ptr;

class Point
: public std::enable_shared_from_this<Point>
{
public:
    Point(int x,int y)
        : _ix(x)
          , _iy(y)
    {}

    //1.
    /* Point * addPoint(Point * pt){ */
    /*     _ix += pt->_ix; */
    /*     _iy += pt->_iy; */
    /*     return this; */
    /* } */

    //2.
    /* shared_ptr<Point> addPoint(Point * pt){ */
    /*     _ix += pt->_ix; */
    /*     _iy += pt->_iy; */
    /*     //临时的shared_ptr对象与sp使用了同一个裸指针 */
        /* return shared_ptr<Point>(this); */

    /*     //创建了新的Point对象，这样可以 */
    /*     return shared_ptr<Point>(new Point(_ix + 1,_iy + 1)); */
    /* } */

    //3.
    shared_ptr<Point> addPoint(Point * pt){
        _ix += pt->_ix;
        _iy += pt->_iy;
        //利用辅助类封装好的函数
        //返回一个共享*this所有权的shared_ptr
        return shared_from_this();
    }

    void print() const{
        cout << "(" << _ix
            << "," << _iy
            << ")" << endl;
    }

    ~Point()
    {
        /* cout << "~Point()" << endl; */
    }
private:
    int _ix;
    int _iy;
};

void test0(){
    shared_ptr<Point> sp(new Point(1,2));
    shared_ptr<Point> sp2(new Point(4,5));

    //1.
    //sp3与sp使用了同一个裸指针初始化
    shared_ptr<Point> sp3(sp->addPoint(sp2.get()));
    cout << sp3.use_count() << endl;
    sp->print();
    sp2->print();
    sp3->print();
    cout << sp.get() << endl;
    cout << sp2.get() << endl;
    cout << sp3.get() << endl;

    //验证第二种问题的方式
    /* cout << "start" << endl; */
    /* sp->addPoint(sp2.get()); */
    /* delete sp.get(); */
    /* cout << "over" << endl; */
}


int main(void){
    test0();
    return 0;
}
